<?php

class DefaultController extends MyUserController
{
	public $modelName = 'User';
	
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
//				'class'=>'ext.kcaptcha.KCaptchaAction',
				'class' => 'CCaptchaAction',
				'backColor' => 0xFFFFFF,
			),
		);
	}
	
	public function actionRegister()
	{
		$model = new $this->modelName;
		$model->scenario = 'register';
		
		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='register-form')
		{
			$model->scenario = 'ajax-register';
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		if(isset($_POST[$this->modelName]))
		{
			$model->attributes=$_POST[$this->modelName];
			if($model->validate())
			{
				$model->setPassword();
				$model->setStatus();
				$model->save(false);
				
				Notification::model()->send(
						Notification::NOTIFY_REGISTRATION, 
						array(Yii::app()->params['systemEmail'] => Yii::app()->name),
						$model->email,
						array(
							'sitename' => Yii::app()->name,
							'username' => $model->username,
							'password' => $_POST[$this->modelName]['password'],
						)
				);
				
				$userModel = new User();
				$userModel = $userModel->findByPk(User::ADMIN_ID);
				Notification::model()->send(
						Notification::NOTIFY_REGISTRATION_ADMIN,
						array(Yii::app()->params['systemEmail'] => Yii::app()->name),
						$userModel->getAttribute('email'),
						array(
							'username' => $model->username,
							'sitename' => Yii::app()->name,
						)
				);				
				Yii::app()->user->setFlash('success', tt('User successfully created'));
				$this->redirect(Yii::app()->homeUrl);
			}
		}
		
		$this->renderPartial('register', array('model'=>$model), false, true);
	}
	
	
	public function actionEdit()
	{
		$model = $this->loadModel(Yii::app()->user->id);
		$oldPassword = $model->password;
		$model->setAttribute("password", "");
		$model->scenario = 'update';

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='edit-form')
		{
			$model->scenario = 'ajax-edit';
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		if(isset($_POST[$this->modelName]))
		{
			$model->attributes = $_POST[$this->modelName];
			if($model->validate())
			{
				if (!empty($model->password))
					$model->setPassword();
				else
					$model->password = $oldPassword;
				$model->save(false);
				
				Yii::app()->user->setFlash('success', tt('User successfully updated'));
				$this->redirect(Yii::app()->homeUrl);
			}
		}

		$this->renderPartial('update',array('model'=>$model), false, true);
	}
	
	
}